var express = require("express");
var router = express.Router();
let crypto = require("crypto"); //加密
let jwt = require("jsonwebtoken");
var userService = require("../service/userService");
// 登录接口
router.post("/login", async (req, res) => {
  try {
    let { username, userpwd } = req.body; //取参数
    let md5 = crypto.createHash("md5");
    userpwd = md5.update(userpwd).digest("hex"); //加密
    let result = await userService.query({
      username,
      userpwd,
    });
    if (result.length) {
      //登录成功
      let info = result[0]; //用户信息
      let token = jwt.sign(
        { id: info._id, username: info.username, usertype: info.usertype },
        "key",
        {
          expiresIn: 1000 * 60 * 30,
        }
      );
      res.json({
        code: 200,
        token,
        msg: "登录成功",
        menu:
          info.usertype == 1
            ? [
                { msg: "批假界面", path: "leave", component: "leave" },
                { msg: "管理学生", path: "student", component: "student" },
                { msg: "数据分析", path: "analysis", component: "analysis" },
              ]
            : [{ msg: "请假界面", path: "addleave", component: "addleave" }],
        usertype: info.usertype,
      });
    } else {
      res.json({
        code: 400,
        msg: "用户名和密码不匹配",
      });
    }
  } catch (err) {
    console.log(err);
  }
});
// 注册接口
router.post("/reg", async (req, res, next) => {
  // let { username, userpwd = "123123" } = req.body; //解构取值 //新增之前判断用户名是否存在
  // let result = await userService.query({ username });
  // if (result.length) {
  //   //用户名存在
  //   res.json({
  //     code: 0,
  //     msg: "该用户已经存在",
  //   });
  // } else {
  //   var md5 = crypto.createHash("md5"); //crypto模块功能是加密并生成各种散列
  //   userpwd = md5.update(userpwd).digest("hex");
  //   userService.register({ username, userpwd, usertype: 2 }).then((data) => {
  //     res.json({
  //       code: 200,
  //       msg: "注册成功",
  //     });
  //   });
  // }
  let token = req.headers.token; //获取身份信息
  let { username } = req.body; //取出用户名 然后解析token
  let md5 = crypto.createHash("md5");
  let userpwd = md5.update("123123").digest("hex");
  let usertype = 2; //新增的是学生
  jwt.verify(token, "key", async (err, info) => {
    if (err || info.usertype != 1) {
      //不是老师
      res.json({
        code: 203,
        msg: "token过期或者权限异常",
      });
    } else {
      //新增之前判断用户名是否存在
      let list = await userService.query({ username });
      if (list.length) {
        //判断用户名存不存在
        res.json({
          code: 204,
          msg: "该用户名已经存在",
        });
      } else {
        //把学生新增
        let result = await userService.register([
          {
            username,
            userpwd,
            usertype,
          },
        ]);
        res.json({
          code: 200,
          result,
        });
      }
    }
  });
});
// 查询学生列表
router.get("/student", (req, res, next) => {
  let token = req.headers.token; //获取头部的token信息
  jwt.verify(token, "key", async (err, info) => {
    //判断是不是老师 是老师就查询所有学生
    if (err || info.usertype != 1) {
      res.json({
        code: 203,
        msg: "token或者权限异常",
      });
    } else {
      let result = await userService.query({ usertype: 2 }); //查询所有学生
      res.json({
        //输出结果
        code: 200,
        list: result,
      });
    }
  });
});
// 删除学生
router.post("/del", (req, res, next) => {
  let token = req.headers.token; //获取头部的token信息
  jwt.verify(token, "key", async (err, info) => {
    //判断是不是老师 是老师就查询所有学生
    if (err || info.usertype != 1) {
      res.json({
        code: 203,
        msg: "token或者权限异常",
      });
    } else {
      let { userid } = req.body;
      let result = await userService.delete({ _id: userid });
      if (result.deletedCount == 1) {
        res.json({
          //输出结果
          code: 200,
          msg: "删除成功",
        });
      } else {
        res.json({
          code: 203,
          msg: "未找到此学生",
        });
      }
    }
  });
});
// 批量新增
router.post("/insertmany", (req, res, next) => {
  let token = req.headers.token;
  jwt.verify(token, "key", async (err, info) => {
    if (err || info.usertype != 1) {
      res.json({
        code: 203,
        msg: "token异常或者权限不够",
      });
    } else {
      let { list } = req.body;
      //但是集合的数据不全
      let md5 = crypto.createHash("md5");
      let userpwd = md5.update("123123").digest("hex");
      //加密
      let usertype = 2;
      // list = JSON.parse(list); //因为集合里面只有对象 对象只有姓名属性
      let usernameList = list.map((item) => item["姓名"]);
      //新增之前 判断是否有用户名存在 如果有就不新增
      let result = await userService.query({ username: { $in: usernameList } });
      if (result.length) {
        //表示有用户存在
        res.json({
          code: 204,
          msg: `有以下用户名已经存在` + result.map((item) => item.username),
        });
      } else {
        //表示没有用户存在
        let arr = list.map((item) => ({
          username: item["姓名"],
          userpwd,
          usertype,
        }));
        let data = await userService.register(arr);
        res.json({
          code: 200,
          data,
        });
      }
    }
  });
});

module.exports = router;
